package com.heima.common.exception;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j //这个注解是用来打印日志文件的
@RestControllerAdvice
@Configuration
public class ExceptionCatch {
    @ExceptionHandler(Exception.class)//只要是Exception或Exception的子类均可被以下这个方法拦截进行处理
    public ResponseResult exception(Exception ex){
        ex.printStackTrace();
        log.error("ExceptionCatch ex:{}",ex);
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"您的网络异常,请稍后重试！");
    }
    //设置全局异常拦截自定义异常
    @ExceptionHandler(CustomException.class)//设置拦截自定义异常
    public ResponseResult CustomException(CustomException ex){
     ex.printStackTrace();
     log.error("CustomException ex:{}",ex);
        AppHttpCodeEnum appHttpCodeEnum = ex.getAppHttpCodeEnum();
        return ResponseResult.errorResult(appHttpCodeEnum);
    }
    /**
     * 参数校验
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleValidationException(MethodArgumentNotValidException ex) {
        log.error("MethodArgumentNotValidException ex:{}", ex);
        ex.printStackTrace();
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, ex.getBindingResult().getFieldError().getDefaultMessage());
    }


}
